package cn.bdqn.Text;

import cn.bdqn.entity.Person;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

public class HibernateTest {
    Configuration cfg;
    SessionFactory sf;
    Session session;
    Transaction tx;
    @Before
    public void init(){
        //读取配置文件
        cfg=new Configuration();
        //默认去加载核心配置文件Hibernate.cfg.xml
        cfg.configure();
        //创建sessionFactory工厂
        sf=cfg.buildSessionFactory();
        //创建员工
        session=sf.openSession();
        //开启事务
        tx = session.beginTransaction();
    }

    @Test
    public void findOne(){
        Person person=session.get(Person.class,1);
        System.out.println(person);
    }

    @Test
    public void updateperson(){
        Person person=session.get(Person.class,1);
        person.setName("王五");
        session.update(person);
    }

    @Test
    public void delPerson(){
        Person person=new Person();
        person.setId(1);
        session.delete(person);
    }

    @Test
    public void findAll(){
        Query query=session.createQuery("from Person");
        List<Person> list=query.list();
        for(Person person:list){
            System.out.println(person);
        }
    }
    @After
    public void destory(){
        tx.commit();
        session.close();
        sf.close();
    }
}
